package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;


    /**
     * 获取指定时间区间内的日期列表
     *
     * @param begin
     * @param end
     * @return
     */
    public List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while (begin.isBefore(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        return dateList;
    }


    /**
     * 统计营业额数据
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //获取订单列表 list
        List<LocalDate> dateList = new ArrayList<LocalDate>();
        //循环获取日期
        while (begin.isBefore(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }

        //遍历订单列表获取金额 ordrers表 状态已完成 下单日期
        //创建列表存金额
        List<Double> turnoverlist = new ArrayList<>();
        dateList.forEach(date -> {
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            Double turnover = ordersMapper.sumByMap(map);
            turnoverlist.add(turnover);
        });


        //构造返回值
        return TurnoverReportVO.builder()
                .dateList(StringUtil.join(dateList.toArray(), ","))
                .turnoverList(StringUtil.join(turnoverlist.toArray(), ","))
                .build();
    }

    /**
     * 用户统计
     */

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //获取日期List  开始日期到结束日期的所有日期

        List<LocalDate> dateList = new ArrayList<>();
        while (begin.isBefore(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        //遍历日期获取新用户List 总用户List
        List<Integer> newUserList = new ArrayList<>();            //再循环遍历
        List<Integer> totalUserList = new ArrayList<>();

        dateList.forEach(date -> {
            Map map = new HashMap();
            map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            Integer newuser = userMapper.selectByCreateTime(map);
            newUserList.add(newuser);

            map.put("begin", null);
            Integer totalUser = userMapper.selectByCreateTime(map);
            totalUserList.add(totalUser);
        });
        //构造VO返回体 string类型用","分割数据ateList newUserList totalUserList
        return UserReportVO.builder()
                .dateList(StringUtil.join(dateList.toArray(), ","))
                .newUserList(StringUtil.join(newUserList.toArray(), ","))
                .totalUserList(StringUtil.join(totalUserList.toArray(), ","))
                .build();
    }

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        //每日订单数，以逗号分隔 orderCountList orders表不需要状态 下单时间即可
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

       for (LocalDate date : dateList) {
                //select count(*) from orders where  order_time between begin and end
                Map map = new HashMap();
                map.put("begin", LocalDateTime.of(date, LocalTime.MIN));
            map.put("end", LocalDateTime.of(date, LocalTime.MAX));
            Integer countCont = ordersMapper.countByDate(map);
            orderCountList.add(countCont);

            //每日有效订单数，以逗号分隔 validOrderCountList orders表需要状态和下单时间
            //有效订单数 validOrderCount 遍历每日有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrder = ordersMapper.validOrderCount(map);
            //总的订单总数    totalOrderCount     Integer
            totalOrderCount += countCont;
            //总的有效订单数   validOrderCount     Integer
            validOrderCount += validOrder;
        }
        ;
        //订单完成率        orderCompletionRate = 每日有效订单数/每日订单数
        if (totalOrderCount == 0) {
            throw new RuntimeException("订单总数为0");
        }
        Double orderCompletionRate = validOrderCount + 0.0 / totalOrderCount;
        //封装VO返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //构造商品名称列表 商品销量列表
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        List<LocalDate> dateList = getDateList(begin, end);

            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", LocalDateTime.of(begin, LocalTime.MIN));
            map.put("end", LocalDateTime.of(end, LocalTime.MAX));
            List<Map> list =ordersMapper.sumTOP10(map);
            //使用遍历list获取值
            for (Map m : list){
                String name = (String) m.get("name");
                Integer number = (Integer) m.get("number");
                nameList.add(name);
                numberList.add(number);
            }
        //输出结果 构建VO SalesTop10ReportVO
        //String: nameList numberList
        return SalesTop10ReportVO.builder()
                .nameList(nameList.toString())
                .numberList(numberList.toString())
                .build();
    }

    @Autowired
    private WorkspaceService workspaceService;
    @Autowired
    private OrdersMapper orderMapper;
    //统计指定时间区间内的销量排名前10
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end,LocalTime.MAX);
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        List<GoodsSalesDTO> salesTop10 = orderMapper.sumTOP10(map);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");
        return SalesTop10ReportVO.builder().nameList(nameList).numberList(numberList).build();
    }
    //导出运营数据报表
    public void exportBusinessData(HttpServletResponse response){
        //1.查询数据库，获取营业数据--查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30); //减30天的时间
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        BusinessDataVO businessDatavo = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
        //2.通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");//在类路径下读取资源返回输入流对象

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取表格文件的Sheet文件
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDatavo.getTurnover()); //第3个单元格
            row.getCell(4).setCellValue(businessDatavo.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDatavo.getNewUsers());
            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDatavo.getValidOrderCount());
            row.getCell(4).setCellValue(businessDatavo.getUnitPrice());
            //填充明细数据
            for(int i=0;i<30;i++){
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
                //获得某一行
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDatavo.getTurnover());
                row.getCell(3).setCellValue(businessDatavo.getValidOrderCount());
                row.getCell(4).setCellValue(businessDatavo.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDatavo.getUnitPrice());
                row.getCell(6).setCellValue(businessDatavo.getNewUsers());
            }
            //3.通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}